<?php

namespace Modules\Coupon\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Coupon\Entities\Coupon;

use Validator;
use ThrowException;
use Auth;

class CouponController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();

        // $options['scopes']['status'] = $req->input('status') == 0 ? 'off' : 'off';

        $list = Coupon::getList($options);

        return $list->generateListResponse();
    }

    public function store(Request $req)
    {
        $rule = [
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $info = $req->all();

        $info['code'] = @$info['code'] ?: strtoupper(str_random(6));

        $item = Coupon::create($info);

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Coupon::getEntity([
            'uuid' => $uuid
        ]);

        $info = $req->input('attributes');

        unset($info['usable_range_text']);

        $item->update($info);

        return [];
    }

    public function show(Request $req, $uuid)
    {
        $rule = [
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Coupon::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Coupon::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();
    }
}
